//
//  texture.mm
//  gl carpchi test
//
//  Created by Realore Realore on 30.09.11.
//  Copyright 2011 Realore Studios. All rights reserved.
//

#include "texture.h"
#include "readpng.h"
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>

Texture::Texture(GLuint tex){
    Tex = tex;
}

Texture::Texture(char filename[]){
    
    bool hasAlpha;
    
    bool success = loadPngImg(filename, width, height, hasAlpha, &pngimage);
    
    if (!success) {
        printf("(pngLoad) %s FAILED.\n", filename);
        NSLog(@"Do real error checking here");
        assert(0);
    } else printf("png load succes");
    
    
    glGenTextures(1, &Tex);
    glBindTexture(GL_TEXTURE_2D, Tex);
    
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);//GL_CLAMP_TO_EDGE
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    
    if(hasAlpha==true){
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, 
                 GL_RGBA, GL_UNSIGNED_BYTE, pngimage);
    }else{        
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, 
                     GL_RGB, GL_UNSIGNED_BYTE, pngimage);        
    }
    //GLint TEXTUREWIDTH;
    
    //glGetTexParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_, &TEXTUREWIDTH);
    
	glEnable( GL_TEXTURE_2D );
	glEnable( GL_BLEND );
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    

}
    
